require('../common/header/index');
require('../common/sidebar/index');
var _util = require('util/util.js')
var _cart_service = require('service/cart-service.js')
var _order_service = require('service/order-service.js')
var vue = require('./../common/vue')
const { toHandlerKey } = require('vue')

var cart_info = new vue({
    el : "#cart_info",
    data : {
        cartItems : [],
        sumprice : 0,
        totaldiscount : 0,
        attrs : [],
        attrindex : 0,
        attrpicture : "",
        shopids : [],
        checkedcoupons : [0],
        usefulcoupons : [],
        allcoupons : [],
        couponsdiscount : 0,
        receivingid: -1,
        receivingAddr: "",
        receivings: []
    },
    methods : {
        selectcoupons : function(){
            this.couponsdiscount = 0;
            this.shopids = [];
            this.checkedcoupons = [];
            var length = this.usefulcoupons.length;
            var i = 0;
            //将选择的优惠卷id放入checkcoupons中，便于后续给到订单
            while( i < length ){
                if ($('input[name='+ this.usefulcoupons[i].shopid +']:checked').val() != undefined && this.shopids.indexOf(this.usefulcoupons[i].shopid) === -1){
                    this.shopids.push(this.usefulcoupons[i].shopid);
                    this.checkedcoupons.push($('input[name='+ this.usefulcoupons[i].shopid +']:checked').val());
                }
                i++;
            }
            i = 0;
            //计算选择的优惠卷的优惠总额
            while( i < length ){
                if(this.checkedcoupons.indexOf(this.usefulcoupons[i].couponid + "") != -1){
                    this.couponsdiscount += this.usefulcoupons[i].discount
                }
                i++
            }
        },
        returnAttrpicture : function(){
            return this.attrpicture;
        },
        returnItempicture : function(index){
            console.log(this.cartItems[index].src)
            return this.cartItems[index].src
        },
        changepicture : function(attrsrc,attrname){
            if(attrname == "颜色"){
                console.log(attrsrc);
                this.attrpicture = attrsrc;
            }
        },
        comfirmAttr : function(index){
            var length = this.attrs.length;
            var i = 0;
            var rate = 1;
            var temp = "";
            //将对应购物车商品的属性全部显示出来，便于后面的选择
            while( i < length ){
                console.log($('input[name='+ this.attrs[i].attrname +']:checked').val())
                if ($('input[name='+ this.attrs[i].attrname +']:checked').val() === undefined){
                    alert("请将属性选择完全噢~");
                    return;
                }
                temp += this.attrs[i].attrname + $('input[name='+ this.attrs[i].attrname +']:checked').prev().text() + " ";
                rate += ($('input[name='+ this.attrs[i].attrname +']:checked').val()-1)
                i++;
            }
            //根据不同属性选择计算新的属性和价格
            this.cartItems[index].price = this.attrs[i-1].price * rate;
            this.cartItems[index].attrdescription = temp;

            var that = this;
            _cart_service.updateCart(this.cartItems[index].itemid,
                function(res){
                    //重新计算购物车相关信息
                    that.cartItems[index].allprice = res[index].allprice;
                    that.totaldiscount = 0;
                    var cartItems = that.cartItems;
                    var length = res.length;
                    var i = 0;
                    while( i  < length ){
                        cartItems[i].specialprice = cartItems[i].allprice*cartItems[i].specialrate;
                        cartItems[i].discount = cartItems[i].allprice - cartItems[i].specialprice;
                        that.sumprice += cartItems[i].allprice;
                        that.totaldiscount += cartItems[i].discount
                        i++;
                    }
                    console.log(res)
                    that.cartItems[index].src = that.attrpicture
                    $("#cancel").click()
                },
                function(err){
                    console.log(err)
                },
                {
                    attrdescription : this.cartItems[index].attrdescription,
                    num : this.cartItems[index].num,
                    price : this.cartItems[index].price
                }
            );

            //重新计算优惠卷
            cart_info.usefulcoupons = [];
            i = 0;
            length = cart_info.cartItems.length;
            var shops = [];
            var sumpshops = [];
            while(i < length){
                var indexat = shops.indexOf(cart_info.cartItems[i].shopid)
                if(indexat === -1){
                    shops.push(cart_info.cartItems[i].shopid);
                    sumpshops[shops.length-1] = cart_info.cartItems[i].specialprice;
                }else{
                    sumpshops[indexat] += cart_info.cartItems[i].specialprice;
                }
                i++;
            }
            console.log(sumpshops)
            i = 0;
            length = cart_info.allcoupons.length;
            while(i < length){
                var indexat = shops.indexOf(cart_info.allcoupons[i].shopid);
                if(sumpshops[indexat] > cart_info.allcoupons[i].fullminus){
                    cart_info.usefulcoupons.push(cart_info.allcoupons[i])
                }
                i++
            }
            console.log(cart_info.allcoupons)
            console.log(cart_info.usefulcoupons)

        },
        cancelAttr : function(index){
            
        },
        updateAttr : function(index){
            var that = this;
            _cart_service.getItemattrs(this.cartItems[index].itemid,
            function(res){
                that.attrs = res;
                that.attrindex = index;
                that.attrpicture = that.cartItems[index].src;
                setTimeout(() => {
                    let attrnum = that.attrs.length;
                    for(let i=0;i<attrnum;i++){
                        $("input:radio[name=" + that.attrs[i].attrname + "]").eq(0).attr("checked",true);
                    }
                }, 200);
            },
            function(err){

            })
        },
        addnum : function(index){
            this.cartItems[index].num++;
            var that = this;
            _cart_service.updateCart(this.cartItems[index].itemid,
            function(res){
                //重新计算购物车相关信息
                that.cartItems[index].allprice = res[index].allprice;
                that.totaldiscount = 0;
                var cartItems = that.cartItems;
                    var length = res.length;
                    var i = 0;
                    while( i  < length ){
                        cartItems[i].specialprice = cartItems[i].allprice*cartItems[i].specialrate;
                        cartItems[i].discount = cartItems[i].allprice - cartItems[i].specialprice;
                        that.sumprice += cartItems[i].allprice;
                        that.totaldiscount += cartItems[i].discount
                        i++;
                    }

                    //重新计算优惠卷
                    cart_info.usefulcoupons = [];
                    i = 0;
                    length = cart_info.cartItems.length;
                    var shops = [];
                    var sumpshops = [];
                    while(i < length){
                        var indexat = shops.indexOf(cart_info.cartItems[i].shopid)
                        if(indexat === -1){
                            shops.push(cart_info.cartItems[i].shopid);
                            sumpshops[shops.length-1] = cart_info.cartItems[i].specialprice;
                        }else{
                            sumpshops[indexat] += cart_info.cartItems[i].specialprice;
                        }
                        i++;
                    }
                    console.log(sumpshops)
                    i = 0;
                    length = cart_info.allcoupons.length;
                    while(i < length){
                        var indexat = shops.indexOf(cart_info.allcoupons[i].shopid);
                        if(sumpshops[indexat] > cart_info.allcoupons[i].fullminus){
                            cart_info.usefulcoupons.push(cart_info.allcoupons[i])
                        }
                        i++
                    }
                    console.log(cart_info.allcoupons)
                    console.log(cart_info.usefulcoupons)
                console.log(res)
            },
            function(err){
                console.log(err)
            },
            {
                attrdescription : this.cartItems[index].attrdescription,
                num : this.cartItems[index].num,
                price : this.cartItems[index].price
            }
            
            )
        },
        subnum : function(index){
            if(this.cartItems[index].num == 1){
                alert("不能再减少了噢~")
            }else{
                this.cartItems[index].num--;
                var that = this;
                _cart_service.updateCart(this.cartItems[index].itemid,
                function(res){
                    //重新计算购物车相关信息
                    that.cartItems[index].allprice = res[index].allprice;
                    that.totaldiscount = 0;
                    var cartItems = that.cartItems;
                    var length = res.length;
                    var i = 0;
                    while( i  < length ){
                        cartItems[i].specialprice = cartItems[i].allprice*cartItems[i].specialrate;
                        cartItems[i].discount = cartItems[i].allprice - cartItems[i].specialprice;
                        that.sumprice += cartItems[i].allprice;
                        that.totaldiscount += cartItems[i].discount
                        i++;
                    }

                    //重新计算优惠卷
                    cart_info.usefulcoupons = [];
                    i = 0;
                    length = cart_info.cartItems.length;
                    var shops = [];
                    var sumpshops = [];
                    while(i < length){
                        var indexat = shops.indexOf(cart_info.cartItems[i].shopid)
                        if(indexat === -1){
                            shops.push(cart_info.cartItems[i].shopid);
                            sumpshops[shops.length-1] = cart_info.cartItems[i].specialprice;
                        }else{
                            sumpshops[indexat] += cart_info.cartItems[i].specialprice;
                        }
                        i++;
                    }
                    console.log(sumpshops)
                    i = 0;
                    length = cart_info.allcoupons.length;
                    while(i < length){
                        var indexat = shops.indexOf(cart_info.allcoupons[i].shopid);
                        if(sumpshops[indexat] > cart_info.allcoupons[i].fullminus){
                            cart_info.usefulcoupons.push(cart_info.allcoupons[i])
                        }
                        i++
                    }
                    console.log(cart_info.allcoupons)
                    console.log(cart_info.usefulcoupons)
                    console.log(res)
                },
                function(err){
                    console.log(err)
                },
                {
                    attrdescription : this.cartItems[index].attrdescription,
                    num : this.cartItems[index].num,
                    price : this.cartItems[index].price
                }
                
                )
            }
        },
        updatenum : function(index){
            if(this.cartItems[index].num <= 1){
                alert("数量不能小于1噢~")
                this.cartItems[index].num=1   
            }
            var that = this;
                _cart_service.updateCart(this.cartItems[index].itemid,
                function(res){
                    that.cartItems[index].allprice = res[index].allprice;
                    that.totaldiscount = 0;
                    var cartItems = that.cartItems;
                    var length = res.length;
                    var i = 0;
                    while( i  < length ){
                        cartItems[i].specialprice = cartItems[i].allprice*cartItems[i].specialrate;
                        cartItems[i].discount = cartItems[i].allprice - cartItems[i].specialprice;
                        that.sumprice += cartItems[i].allprice;
                        that.totaldiscount += cartItems[i].discount
                        i++;
                    }

                    //重新计算优惠卷
                    cart_info.usefulcoupons = [];
                    i = 0;
                    length = cart_info.cartItems.length;
                    var shops = [];
                    var sumpshops = [];
                    while(i < length){
                        var indexat = shops.indexOf(cart_info.cartItems[i].shopid)
                        if(indexat === -1){
                            shops.push(cart_info.cartItems[i].shopid);
                            sumpshops[shops.length-1] = cart_info.cartItems[i].specialprice;
                        }else{
                            sumpshops[indexat] += cart_info.cartItems[i].specialprice;
                        }
                        i++;
                    }
                    console.log(sumpshops)
                    i = 0;
                    length = cart_info.allcoupons.length;
                    while(i < length){
                        var indexat = shops.indexOf(cart_info.allcoupons[i].shopid);
                        if(sumpshops[indexat] > cart_info.allcoupons[i].fullminus){
                            cart_info.usefulcoupons.push(cart_info.allcoupons[i])
                        }
                        i++
                    }
                    console.log(cart_info.allcoupons)
                    console.log(cart_info.usefulcoupons)
                    console.log(res)
                    console.log(res)
                },
                function(err){
                    console.log(err)
                },
                {
                    attrdescription : this.cartItems[index].attrdescription,
                    num : this.cartItems[index].num,
                    price : this.cartItems[index].price
                }
                
                )
        },
        removecartItem : function(index){
            var that = this;
            _cart_service.removeCartItem(this.cartItems[index].itemid,
            function(res){
                console.log(res)
                //删除购物车后重新获取购物车商品信息，保证异步刷新
                _cart_service.getCartItemList(
                    function(res){

                        //获取购物车信息
                       cart_info.cartItems = res;
                       var cartItems = cart_info.cartItems;
                       var length = res.length;
                       var i = 0;
                       cart_info.sumprice = 0;
                       cart_info.totaldiscount = 0;
                       while( i  < length ){
                        cartItems[i].specialprice = cartItems[i].allprice*cartItems[i].specialrate;
                        cartItems[i].discount = cartItems[i].allprice - cartItems[i].specialprice;
                        cart_info.sumprice += cartItems[i].allprice;
                        cart_info.totaldiscount += cartItems[i].discount
                        i++;
                       }

                       //获取购物车信息后，在获取信息基础上再进行优惠卷的更新
                       cart_info.usefulcoupons = [];
                       i = 0;
                       length = cart_info.cartItems.length;
                       var shops = [];
                       var sumpshops = [];
                       while(i < length){
                           var indexat = shops.indexOf(cart_info.cartItems[i].shopid)
                           if(indexat === -1){
                               shops.push(cart_info.cartItems[i].shopid);
                               sumpshops[shops.length-1] = cart_info.cartItems[i].specialprice;
                           }else{
                               sumpshops[indexat] += cart_info.cartItems[i].specialprice;
                           }
                           i++;
                       }
                       console.log(sumpshops)
                       i = 0;
                       length = cart_info.allcoupons.length;
                       while(i < length){
                           var indexat = shops.indexOf(cart_info.allcoupons[i].shopid);
                           if(sumpshops[indexat] > cart_info.allcoupons[i].fullminus){
                               cart_info.usefulcoupons.push(cart_info.allcoupons[i])
                           }
                           i++
                       }
                       console.log(cart_info.allcoupons)
                       console.log(cart_info.usefulcoupons)
                    },
                    function(res){
                        console.log("ERROR..*..")
                    }
                )
            },
            function(err){
                console.log(err)
            },
            )
        },
        clearCart: function() {
            if(this.receivingid === -1){
                $("#receiving-form").modal();
                return ;
            }
            let _this = this;
            let data = {
                receivingid: _this.receivingid,
                couponids: _this.checkedcoupons.join(",")
            }
            console.log(data);
            _cart_service.clearCart(function(res) {
                window.location.href = "/view/orders_all.html?status=0";
            }, function(err) {
                console.log(err);
            }, data)
        },
        fetchReceivings: function(){
            let _this = this;
            _order_service.getReceivings(function(res) {
                _this.receivings = res;
                setTimeout(() => {
                    // $("input:radio[name=receiving-choice]").eq(0).attr("checked",true);
                    // _this.changeReceiving();
                    // alert(_this.receivingid);
                }, 200);
                
            }, function(err) {
                console.log(err);
            });
        },
        changeReceiving: function(){
            this.receivingAddr = $("input:radio[name=receiving-choice]:checked").next().text();
        },
        getCartNums: function() {
            let self = this;
            if (_util.checkLogin()) {
                _cart_service.getCartNums(
                    function (res) {
                        self.cartItemsNum = res;
                    },
                    function (errMsg) {
                        console.log(errMsg)
                    }
                )
            }
            return this.cartItemsNum
        }
    },
    //初始化vue对象，渲染数据
    created : function(){
        //获取的购物车商品对象
        _cart_service.getCartItemList(
            function(res){
               cart_info.cartItems = res;
               var cartItems = cart_info.cartItems;
               var length = res.length;
               var i = 0;
               while( i  < length ){
                cartItems[i].specialprice = cartItems[i].allprice*cartItems[i].specialrate;
                cartItems[i].discount = cartItems[i].allprice - cartItems[i].specialprice;
                cart_info.sumprice += cartItems[i].allprice;
                cart_info.totaldiscount += cartItems[i].discount
                i++;
               }
            },
            function(res){
                console.log("ERROR..*..")
            }
        ),
        //获取所有的优惠卷
        _cart_service.getcoupons(
            function(res){
                cart_info.allcoupons = res;
                cart_info.usefulcoupons = [];
                var i = 0;
                var length = cart_info.cartItems.length;
                //保存优惠卷商商铺的id
                var shops = [];
                //保存购物车对应商铺的购买总金额，用来判断优惠卷是否可用
                var sumpshops = [];
                while(i < length){
                    var indexat = shops.indexOf(cart_info.cartItems[i].shopid)
                    if(indexat === -1){
                        shops.push(cart_info.cartItems[i].shopid);
                        sumpshops[shops.length-1] = cart_info.cartItems[i].specialprice;
                    }else{
                        sumpshops[indexat] += cart_info.cartItems[i].specialprice;
                    }
                    i++;
                }
                console.log(sumpshops)
                //用来判断哪些优惠卷可用
                i = 0;
                length = cart_info.allcoupons.length;
                while(i < length){
                    var indexat = shops.indexOf(cart_info.allcoupons[i].shopid);
                    //购物车商铺总金额大于满减，就存入
                    if(sumpshops[indexat] > cart_info.allcoupons[i].fullminus){
                        cart_info.usefulcoupons.push(cart_info.allcoupons[i])
                    }
                    i++
                }
                console.log(cart_info.allcoupons)
                console.log(cart_info.usefulcoupons)
            },
            function(err){

            }
        )

        this.fetchReceivings();
    }

})
